import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs';
import { FormControl } from '@angular/forms';
import { ServerConnectionStatusService } from '../../../service/server-connection-status/server-connection-status.service';
import { ScrewService } from '../../../service/screw/screw.service';
import { finalize, timeout } from 'rxjs/operators';

@Component({
  selector: 'app-screw-count',
  templateUrl: './screw-count.component.html',
  styleUrls: ['./screw-count.component.css']
})
export class ScrewCountComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('autoFocusedInput') autoFocusedInput: ElementRef;

  private subscribedServices: Subscription[] = [];

  isServerConnected = false;
  isSubmitButtonTooltipVisible = false;

  corpName = new FormControl();

  isBusy = false;

  progressBarCurrentStep = 0;

  isExecutionResultError: boolean = null;
  executionResult = '';

  constructor(private serverConnectionStatusService: ServerConnectionStatusService,
              private screwService$: ScrewService) {
  }

  ngOnInit(): void {
    this.subscribedServices.push(this.serverConnectionStatusService.isServerConnected.subscribe(it => {
      this.isServerConnected = it;
    }));
  }

  ngAfterViewInit(): void {
    this.autoFocusedInput.nativeElement.focus();
  }

  ngOnDestroy(): void {
    for (const svc of this.subscribedServices) {
      svc.unsubscribe();
    }
  }

  submitCount(): void {
    if (this.isServerConnected) {
      this.progressBarCurrentStep = 1;
      this.isBusy = true;
      this.isExecutionResultError = null;
      this.executionResult = '';

      this.screwService$.count(this.corpName.value).pipe(
        finalize(() => {
          this.isBusy = false;
        })).pipe(timeout(60000)).subscribe(
        txId => {
          this.progressBarCurrentStep = 2;
          this.isExecutionResultError = false;
          this.executionResult = `螺丝库存数量：${txId}`;
        }, err => {
          this.isExecutionResultError = true;
          if (err.status === 500) {
            this.executionResult = `服务器内部错误：${err.error}`;
          } else {
            this.progressBarCurrentStep = 2;
            this.executionResult = `错误：`;
            for (const errMsg of err.error) {
              this.executionResult += `\n${errMsg}`;
            }
          }
        });
    } else {
      this.isSubmitButtonTooltipVisible = true;
    }
  }

  reset(): void {
    this.progressBarCurrentStep = 0;
    this.isExecutionResultError = null;
    this.executionResult = '';

    this.corpName.setValue('');

    this.autoFocusedInput.nativeElement.focus();
  }

}
